<?php


namespace App\Models\OpenShop\Site;


use App\Enums\OpenShop\MissionTemplateEnum;
use App\Models\BaseModel;
use App\Models\Traits\KfSoftDeletes;

class OpenShopMissionTemplateModel extends BaseModel
{
    use KfSoftDeletes;

    protected $table = 'open_shop_mission_template';

    protected $fillable = [
        'id',
        'name',
        'missionType',
        'mainStep',
        'stepStatus',
        'handlerType',
        'handlerDay',
        'exceptionHandlerId',
        'handlerRole',
        'handlerRule',
        'extendHandler',
        'sort',
    ];

    public function getMissionTypeTextAttribute()
    {
        return MissionTemplateEnum::MISSION_TYPE_TEXT[$this->missionType] ?? '';
    }

    public function getMainStepTextAttribute()
    {
        return MissionTemplateEnum::MAIN_STEP_TEXT[$this->mainStep] ?? '';
    }

    public function getStepStatusTextAttribute()
    {
        return MissionTemplateEnum::STEP_STATUS_TEXT[$this->stepStatus] ?? '';
    }

    public function getHandlerTypeTextAttribute()
    {
        return MissionTemplateEnum::HANDLER_TYPE_TEXT[$this->handlerType] ?? '';
    }

    public function getHandlerRoleTextAttribute()
    {
        return MissionTemplateEnum::HANDLER_ROLE_TEXT[$this->handlerRole] ?? '';
    }

    public function getHandlerRuleTextAttribute()
    {
        return MissionTemplateEnum::HANDLER_RULE_TEXT[$this->handlerRule] ?? '';
    }

    public function getExtendHandlerTextAttribute()
    {
        return MissionTemplateEnum::EXTEND_HANDLER_TEXT[$this->extendHandler] ?? '';
    }

    public function addData()
    {
        $this->stepStatus         = $this->stepStatus ?? 0;
        $this->handlerDay         = $this->handlerDay ?? 0;
        $this->exceptionHandlerId = $this->exceptionHandlerId ?? 0;
        $this->handlerRole        = $this->handlerRole ?? 0;
        $this->handlerRule        = $this->handlerRule ?? 0;
        $this->extendHandler      = $this->extendHandler ?? 0;

        $arr = [];
        foreach ($this->fillable as $field) {
            $arr[$field] = $this->$field;
        }

        return self::query()->create($arr);
    }

    public function editData(int $id): int
    {
        $arr = [];
        foreach ($this->fillable as $field) {
            if ($this->$field === null) {
                continue;
            }

            $arr[$field] = $this->$field;
        }

        if (!$arr) {
            return 0;
        }

        return self::query()->where('id', $id)->update($arr);
    }
}
